<template>
  <div class="template-to-file-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>模板导出</span>
        </div>
      </template>
      
      <el-form 
        ref="formRef"
        :model="formData" 
        :rules="formRules" 
        label-width="120px"
        class="export-form"
      >
        <!-- 模板选择 -->
        <el-form-item label="模板文件" prop="templateId" required>
          <div class="template-selector">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索模板文件"
              clearable
              style="width: 300px; margin-right: 10px;"
              @keyup.enter="handleSearchTemplate"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleSearchTemplate" :loading="templateLoading">
              搜索
            </el-button>
          </div>
          
          <!-- 当前选中的模板 -->
          <div v-if="selectedTemplate" class="selected-template">
            <el-alert
              :title="`当前模板：${selectedTemplate.file_name}`"
              type="success"
              :closable="false"
              show-icon
            />
          </div>
          
          <!-- 模板搜索结果 -->
          <div v-if="templateList.length > 0" class="template-results">
            <el-table 
              :data="templateList" 
              style="width: 100%; margin-top: 10px;"
              @row-click="handleSelectTemplate"
              highlight-current-row
            >
              <el-table-column prop="file_name" label="文件名" min-width="300" />
              <el-table-column prop="upload_time" label="上传时间" width="180" align="center">
                <template #default="scope">
                  {{ formatDateTime(scope.row.upload_time) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>

        <!-- 学期设置 -->
        <el-form-item label="学期" prop="season" required>
          <div class="season-input">
            <el-input-number
              v-model="formData.startYear"
              :min="2020"
              :max="9999"
              placeholder="开始年份（如：2024）"
              style="width: 150px; margin-right: 10px;"
              @change="updateSeason"
            />
            <span style="margin-right: 10px;">-</span>
            <el-input-number
              v-model="formData.endYear"
              :min="2020"
              :max="9999"
              placeholder="结束年份"
              style="width: 150px; margin-right: 10px;"
              @change="updateSeason"
            />
            <el-radio-group v-model="formData.seasonType" @change="updateSeason">
              <el-radio label="秋">秋季学期</el-radio>
              <el-radio label="春">春季学期</el-radio>
            </el-radio-group>
          </div>
          
          <!-- 格式化后的学期显示 -->
          <div class="formatted-season">
            <el-alert
              :title="`格式化后的学期：${formattedSeason}`"
              type="info"
              :closable="false"
              show-icon
            />
          </div>
        </el-form-item>

        <!-- 专业和年级选择 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年级" prop="grade" required>
              <el-input-number 
                v-model="formData.grade" 
                :min="2020" 
                :max="9999"
                placeholder="请输入年级（如：2024）"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业" prop="major" required>
              <el-select 
                v-model="formData.major" 
                placeholder="请选择专业" 
                style="width: 100%;"
                :loading="majorsLoading"
                :remote-method="remoteMethod"
                :remote="true"
                :filterable="true"
                :reserve-keyword="false"
              >
                <el-option
                  v-for="major in majorsForSelect"
                  :key="major.id"
                  :label="major.name"
                  :value="major.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 课程选择 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="课程序号">
              <el-input 
                v-model="formData.courseId" 
                placeholder="可选，直接输入课程序号"
                style="width: 100%;"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程名称">
              <el-autocomplete
                v-model="formData.courseName"
                :fetch-suggestions="queryCourseNames"
                placeholder="可选，输入课程名称"
                style="width: 100%;"
                clearable
                :trigger-on-focus="false"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 文件输出名称 -->
        <el-form-item label="输出文件名">
          <el-input 
            v-model="formData.fileOutputName" 
            placeholder="可选，自定义下载后的文件名（不填则使用默认名称）"
            style="width: 100%;"
            clearable
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleExport" :loading="exporting">
            开始导出
          </el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button @click="handleBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import fileApi from '../api/fileApi.js'
import majorApi from '../api/majorApi.js'
import courseApi from '../api/courseApi.js'
import { createTask } from '../api/taskApi.js'

// 定义props
const props = defineProps({
  templateData: {
    type: Object,
    default: null
  }
})

// 响应式数据
const formRef = ref()
const templateLoading = ref(false)
const exporting = ref(false)
const majorsLoading = ref(false)
const searchKeyword = ref('')
const templateList = ref([])
const selectedTemplate = ref(null)
const majorsForSelect = ref([])

// 表单数据
const formData = reactive({
  templateId: '',
  startYear: new Date().getFullYear(),
  endYear: new Date().getFullYear() + 1,
  seasonType: '秋',
  season: '',
  grade: new Date().getFullYear(),
  major: '',
  courseId: '',
  courseName: '',
  fileOutputName: ''
})

// 表单验证规则
const formRules = {
  templateId: [
    { required: true, message: '请选择模板文件', trigger: 'change' }
  ],
  season: [
    { required: true, message: '请设置学期', trigger: 'change' }
  ],
  grade: [
    { required: true, message: '请输入年级', trigger: 'blur' }
  ],
  major: [
    { required: true, message: '请选择专业', trigger: 'change' }
  ]
}

// 学期格式化
const LOCAL_KEY = 'season_format_str'
const defaultFormat = '{{yyyy1}}-{{yyyy2}}学年{{s}}季学期'

// 计算格式化后的学期
const formattedSeason = computed(() => {
  const formatStr = localStorage.getItem(LOCAL_KEY) || defaultFormat
  let result = formatStr
  result = result.replace(/\{\{yyyy1\}\}/g, formData.startYear)
  result = result.replace(/\{\{yyyy2\}\}/g, formData.endYear)
  result = result.replace(/\{\{s\}\}/g, formData.seasonType)
  result = result.replace(/\{\{s_int\}\}/g, formData.seasonType === '秋' ? '1' : '2')
  return result
})

// 更新学期
const updateSeason = () => {
  formData.season = formattedSeason.value
}

// 搜索模板
const handleSearchTemplate = async () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  
  templateLoading.value = true
  try {
    const params = {
      size: 10,
      currentPage: 1,
      filename: searchKeyword.value
    }
    
    const response = await fileApi.queryTemplateList(params)
    if (response.success === 0) {
      templateList.value = response.data.data || []
    } else {
      ElMessage.error(response.message || '搜索模板失败')
    }
  } catch (error) {
    console.error('搜索模板失败:', error)
    ElMessage.error('搜索模板失败')
  } finally {
    templateLoading.value = false
  }
}

// 选择模板
const handleSelectTemplate = (template) => {
  selectedTemplate.value = template
  formData.templateId = template.id
}

// 专业搜索
const remoteMethod = async (query) => {
  if (query) {
    majorsLoading.value = true
    try {
      const response = await majorApi.fuzzyQueryMajor(query)
      if (response.success === 0) {
        majorsForSelect.value = response.data || []
      } else {
        majorsForSelect.value = []
      }
    } catch (error) {
      console.error('搜索专业失败:', error)
      majorsForSelect.value = []
    } finally {
      majorsLoading.value = false
    }
  } else {
    majorsForSelect.value = []
  }
}

// 课程名称搜索
const queryCourseNames = async (queryString, callback) => {
  if (queryString) {
    try {
      const response = await courseApi.fuzzyQueryCourse(queryString)
      if (response.success === 0) {
        const courseNames = response.data || []
        const suggestions = courseNames.slice(0, 5).map(name => ({ value: name }))
        callback(suggestions)
      } else {
        callback([])
      }
    } catch (error) {
      console.error('搜索课程失败:', error)
      callback([])
    }
  } else {
    callback([])
  }
}

// 导出
const handleExport = async () => {
  try {
    await formRef.value.validate()
    
    // 验证课程信息
    if (!formData.courseId && !formData.courseName) {
      ElMessage.error('课程名称和课程ID至少需要提供一个')
      return
    }
    
    exporting.value = true
    
    const params = {
      taskType: 'templateToFile',
      templateId: formData.templateId,
      season: formData.season,
      grade: formData.grade,
      major: formData.major
    }
    
    if (formData.courseId) {
      params.courseId = formData.courseId
    }
    if (formData.courseName) {
      params.courseName = formData.courseName
    }
    if (formData.fileOutputName) {
      params.fileOutputName = formData.fileOutputName
    }
    
    const response = await createTask(params)
    
    if (response.success === 0) {
      ElMessage.success('任务创建成功')
      // 跳转到任务查看页面
      const menuEvent = new CustomEvent('menuSelect', {
        detail: { menuIndex: 'material-3' }
      })
      window.dispatchEvent(menuEvent)
    } else {
      ElMessage.error(response.message || '任务创建失败')
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    exporting.value = false
  }
}

// 重置
const handleReset = () => {
  formRef.value.resetFields()
  selectedTemplate.value = null
  templateList.value = []
  searchKeyword.value = ''
  formData.startYear = new Date().getFullYear()
  formData.endYear = new Date().getFullYear() + 1
  formData.seasonType = '秋'
  updateSeason()
}

// 返回
const handleBack = () => {
  // 切换到模板管理菜单
  const menuEvent = new CustomEvent('menuSelect', {
    detail: { menuIndex: 'material-1' }
  })
  window.dispatchEvent(menuEvent)
}

// 格式化时间
const formatDateTime = (timestamp) => {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 监听模板数据变化
watch(() => props.templateData, (newData) => {
  if (newData && newData.templateId && newData.templateName) {
    selectedTemplate.value = {
      id: newData.templateId,
      file_name: newData.templateName
    }
    formData.templateId = newData.templateId
  }
}, { immediate: true })

// 初始化
onMounted(() => {
  // 初始化学期
  updateSeason()
})
</script>

<style scoped>
.template-to-file-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.export-form {
  max-width: 800px;
  margin: 0 auto;
}

.template-selector {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.selected-template {
  margin-bottom: 10px;
}

.template-results {
  margin-top: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.season-input {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.formatted-season {
  margin-top: 10px;
}
</style> 